package repository;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;

import model.storage;

public class storageRepository {
	private String fileName;
	
	public storageRepository(String fileName){
		this.fileName = fileName;
	}

	/**
	 * Get all data from the file and parse it to the array of models
	 *
	 */
	public ArrayList<storage> getDataFromFile() {
		ArrayList<storage> dataFromDB = new ArrayList<storage>();
	    String detail = new String();
	    storage st;
	    BufferedReader empdtil = null;
	    try {
	    	empdtil = new BufferedReader(new FileReader(fileName));
	        while ((detail = empdtil.readLine()) != null) {
	        	if (detail != ""){
	        		System.out.println(detail);	
	        		st = new storage();
	        		st.fillObject(detail); 
	        		dataFromDB.add(st);
	        	}
	        }
	    }
	    catch (Exception e) {
	    	if (empdtil != null)
			try {
				empdtil.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
	    }
	    return dataFromDB;
	}
	/**
	 * Save the data to the file.
	 *
	 * @param  	dataFromDB - the list of data to save 
	 */
	public void saveDataToFile(ArrayList<storage> dataFromDB) {
		try {
			FileWriter out = new FileWriter(new File(fileName).getAbsoluteFile());
			for(storage st : dataFromDB)
			{
				out.write(st.toString());
				out.write(System.getProperty("line.separator"));
			}
        	out.close();
        } catch(IOException e) {
        	throw new RuntimeException(e);
		} 
	}	
	
	/**
	 * Add the new store to the database.
	 *
	 * @param  	st - the object to add 
	 */
	public void addNewGood(storage st) {       
        try {
        	FileWriter out = new FileWriter(new File(fileName).getAbsoluteFile(), true);
        	try {
        		out.write(st.toString());
        		out.write(System.getProperty("line.separator"));
        	} finally {
        		out.close();
        	}
        	} catch(IOException e) {
        		throw new RuntimeException(e);
        	} 
	}
}
